package com.cloud.school.app.service.impl;

import com.cloud.school.app.entity.TbLike;
import com.cloud.school.app.mapstruct.ILikeConvertMapper;
import com.cloud.school.app.model.LikeModel;
import com.cloud.school.app.model.UserModel;
import com.cloud.school.app.repository.TbLikeMapper;
import com.cloud.school.app.service.LikeService;
import com.cloud.school.app.service.UserService;
import com.cloud.school.app.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName LikeServiceImpl
 * @Description TODO
 * @Author 36297
 * @Date 2018/12/14 0:54
 * @Version 1.0
 */
@Service
public class LikeServiceImpl implements LikeService {
    @Autowired
    private TbLikeMapper tbLikeMapper;
    @Autowired
    private ILikeConvertMapper likeConvertMapper;
    @Autowired
    private IdWorker likeIdWorker;
    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public boolean save(LikeModel likeModel) {
        TbLike like = likeConvertMapper.modelToEntity(likeModel);
        like.setId(likeIdWorker.nextId());
        like.setCreateTime(System.currentTimeMillis());
        return tbLikeMapper.insertSelective(like) > 0;
    }

    @Override
    public List<LikeModel> selectByShowId(Long showId) {
        TbLike like = new TbLike();
        like.setShowId(showId);
        List<LikeModel> likeModels = likeConvertMapper.entityToModel(tbLikeMapper.select(like));
        appendUser(likeModels);
        return likeModels;
    }

    @Override
    public List<LikeModel> selectByShowIds(List<Long> showIds) {
        showIds = showIds.stream().distinct().collect(Collectors.toList());
        Example example = new Example(TbLike.class);
        example.createCriteria().andIn("showId", showIds);
        List<LikeModel> likeModels = likeConvertMapper.entityToModel(tbLikeMapper.selectByExample(example));
        appendUser(likeModels);
        return likeModels;
    }

    @Override
    @Transactional
    public boolean deleteByShowId(Long showId) {
        TbLike like = new TbLike();
        like.setShowId(showId);
        return tbLikeMapper.delete(like) > 0;
    }

    private void appendUser(List<LikeModel> result) {
        List<Long> uids = result.stream().map(l -> l.getCreateUid()).filter(id -> id != null).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(uids)) {
            Map<Long, UserModel> userModelMap = userService.queryDetailByIds(uids).stream().collect(Collectors.toMap(UserModel::getId, u -> u));
            result.forEach(c -> c.setCreator(userModelMap.get(c.getCreateUid())));
        }
    }
}
